import { reqAddUser } from '../../api'
import profileRender from './profile.art'

// 给文件上传的输入框绑定change事件 => 用于选择图片后, 自动显示预览
document.getElementById('profile').onchange = (e) => {
  const fileReader = new FileReader()
  const file = e.target.files[0]
  // console.log(e.target.files)
  fileReader.readAsDataURL(file)
  fileReader.onload = () => {
    const profile = fileReader.result
    console.log(profile)
    const html = profileRender({profile})
    const profileContainerEle = document.getElementById('profileContainer')
    profileContainerEle.innerHTML = html
  }
}

// 得到表单
const addForm = document.getElementById('addForm')
// 绑定提交事件
addForm.onsubmit = async (e) => {
  // 阻止默认行为
  e.preventDefault()
  // 收集表单数据
  const formData = new FormData(addForm)
  // console.log(formData.get('username'))
  // console.log(formData.get('pwd'))
  // console.log(formData.get('profileFile'))
  // 提交添加用户请求
  const result = await reqAddUser(formData)
  if (result.code==='2000') {
    // 成功后跳转到用户列表页
    window.location = '/users.html'
  } else {
    alert(result.message)
  }
}